package com.example.airobotsettings.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.airobotsettings.entity.BackgroundUser;
import com.example.airobotsettings.dao.LoginDto;
import com.example.airobotsettings.dao.Result;
import com.example.airobotsettings.mapper.BackgroundUserMapper;
import com.example.airobotsettings.service.UserService;
import com.example.airobotsettings.util.JwtUtil;
import com.example.airobotsettings.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private BackgroundUserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    public UserServiceImpl(BackgroundUserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Override
    public Result<LoginDto> login(String username, String password){
        /**
         * 判断用户名和密码是否为空
         */
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return Result.error(400,"用户名或密码不能为空");
        }

        /**
         * 判断用户名和密码是否正确
         */

        LambdaQueryWrapper<BackgroundUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BackgroundUser::getUsername,username);
        BackgroundUser user = userMapper.selectOne(wrapper);

        if (user == null){
            return Result.error(400,"用户名错误");
        }

        String md5Input = MD5Util.md5(password);
        if (!user.getPassword().equals(md5Input)){
            return Result.error(401,"密码错误");
        }

        /**
         * 更新登录信息
         */
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 生成token
        String token = jwtUtil.generateToken(user.getUsername());
        
        // 创建LoginDto对象并设置属性
        LoginDto loginDto = new LoginDto();
        loginDto.setUsername(user.getUsername());
        loginDto.setToken(token);
        loginDto.setRealName(user.getRealName());
        
        return Result.success(loginDto);
    }


    /**
     * 注册
     * @param username
     * @param password
     * @param realName
     * @param email
     * @return
     */
    @Override
    public Result<LoginDto> register(String username, String password, String realName, String email) {
        // 参数校验：检查用户名和密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Result.error(400, "用户名或密码不能为空");
        }
        
        // 检查用户名是否已存在
        LambdaQueryWrapper<BackgroundUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BackgroundUser::getUsername, username);
        BackgroundUser existingUser = userMapper.selectOne(wrapper);
        
        if (existingUser != null) {
            return Result.error(400, "用户名已存在");
        }
        
        // 创建新用户对象
        BackgroundUser newUser = new BackgroundUser();
        newUser.setUsername(username);
        // 使用MD5加密密码
        newUser.setPassword(MD5Util.md5(password));
        newUser.setRealName(realName);
        newUser.setEmail(email);
        newUser.setStatus("active");
        newUser.setCreatedAt(LocalDateTime.now());
        newUser.setUpdatedAt(LocalDateTime.now());
        
        // 保存用户到数据库
        int result = userMapper.insert(newUser);
        
        if (result <= 0) {
            return Result.error(500, "注册失败，请稍后重试");
        }
        
        // 生成token
        String token = jwtUtil.generateToken(username);
        
        // 创建LoginDto对象并设置属性
        LoginDto loginDto = new LoginDto();
        loginDto.setUsername(username);
        loginDto.setToken(token);
        loginDto.setRealName(realName);
        
        return Result.success(loginDto);
    }


    /**
     * 修改密码
     * @param username
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public Result<Void> changePassword(String username, String oldPassword, String newPassword) {
        // 参数校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)) {
            return Result.error(400, "用户名、旧密码和新密码不能为空");
        }

        // 查询用户
        LambdaQueryWrapper<BackgroundUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BackgroundUser::getUsername, username);
        BackgroundUser user = userMapper.selectOne(wrapper);

        if (user == null) {
            return Result.error(400, "用户不存在");
        }

        // 验证旧密码
        String md5OldPassword = MD5Util.md5(oldPassword);
        if (!user.getPassword().equals(md5OldPassword)) {
            return Result.error(401, "旧密码错误");
        }

        // 更新新密码
        user.setPassword(MD5Util.md5(newPassword));
        userMapper.updateById(user);

        // 使该用户的所有token失效
        jwtUtil.invalidateAllUserTokens(username);

        return Result.success(null);
    }

    /**
     * 退出登录
     * @param token 用户的登录token
     * @return 退出结果
     */
    @Override
    public Result<Void> logout(String token) {
        if (StringUtils.isEmpty(token)) {
            return Result.error(400, "token不能为空");
        }

        try {
            // 验证token是否有效
            String username = jwtUtil.validateToken(token);
            if (username == null) {
                return Result.error(401, "无效的token");
            }

            // 将token加入黑名单
            jwtUtil.invalidateToken(token);

            return Result.success(null);
        } catch (Exception e) {
            return Result.error(500, "退出登录失败：" + e.getMessage());
        }
    }
}
